<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/3/14
 * Time: 16:54
 */

namespace app\api\validate;


use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    /*
     * 获取所有http传过来的参数
     * 对参数进行校验
     * */
    public function goCheck(){
        $request = Request::instance();
        $params = $request->param();

        $result = $this->batch()->check($params);
        if (!$result){
            //抛出自定义异常
            $e = new ParameterException([
                'msg' => $this->error
            ]);
            throw $e;
            /*$error = $this->error;
            throw new Exception($error);*/
        }else{
            return true;
        }
    }

    //自定义验证-验证正整数
    protected function isPositiveInteger($value, $rule = '', $date = '',$field = ''){
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0){
            return true;
        }else{
            return false;
        }
    }

    //自定义验证-验证参数值为空
    protected function isNotEmpty($value, $rule = '', $date = '',$field = ''){
        if (empty($value)){
            return false;
        }else{
            return true;
        }
    }

    //自定义验证-验证手机号
    //"020-81167888"  \d{3}-\d{8}|\d{4}-\{7,8}
    protected function isMobile($value)
    {
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $ruleTelephone = '/\d{3}-\d{8}|\d{4}-\{7,8}/';
        $resultMobile = preg_match($rule, $value);
        $resultTelephone = preg_match($ruleTelephone, $value);
        if ($resultMobile or $resultTelephone) {
            return true;
        } else {
            return false;
        }
    }

    //对post传递过来的数据进行过滤，只拿取在验证规则里验证的参数
    public function getDateByRule($arrays){
        if ( array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays) ){
            //不允许包含user_id或者uid，防止恶意覆盖user_id外键
            throw new ParameterException([
                'msg' => '参数中包含非法参数名user_id或者uid'
            ]);
        }
        $newArray = [];
        foreach ( $this->rule as $key => $value) {
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }

    //对post传递过来的数据进行过滤，只拿取在验证规则里验证的参数
    public function getDateByRuleByKey($arrays){
        if ( array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays) ){
            //不允许包含user_id或者uid，防止恶意覆盖user_id外键
            throw new ParameterException([
                'msg' => '参数中包含非法参数名user_id或者uid'
            ]);
        }
        $newArray = array_intersect_key($arrays, $this->rule);
        return $newArray;
    }

}




